<?php
	/**
	 * NL_Exception
	 * 错误处理及异常处理类
	 * Developer : Necylus@126.com  , Copyright (C) Grayant.com.
	 */
	
	// 预定义 日志保存路径, 物理绝对路径, 不要以/结尾
	//$__NL__LOG_SAVE_PATH = '';
	class NL_Exception {
		const VERSION = '2.0.0';
		public $message = null;
		public $code = null;
		public $file = null;
		public $line = null;
		static public function error_handler($message, $code, $file = null, $line = null){
			if($code>7)
				self::message($message, $code, $file, $line);
		}
		static public function exception_handler(Exception $e){
			self::message($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine());
		}
		static public function message($message, $code, $file = null, $line = null){
			global $_NL_DebugMode,$__NL__LOG_SAVE_PATH;
	
			if($_NL_DebugMode){		
				echo '<pre>';
				echo "Error Code: {$code}\r\n";
				echo "Error Message: {$message}\r\n";
				if($file) echo "Error File: {$file}\r\n";
				if($line) echo "Error Line: {$line}\r\n";
				echo '<pre>';
			}
			else {
				//save log
				if(is_writable($__NL__LOG_SAVE_PATH)){
					$path = $__NL__LOG_SAVE_PATH.'/'.date("Ymd").'.csv';
					$SCRIPT_URL = $_SERVER['REQUEST_URI'] ? $_SERVER['REQUEST_URI'] : $_SERVER['SCRIPT_NAME'].($_SERVER['QUERY_STRING']?"?".$_SERVER['QUERY_STRING']:'');
					$data = array(date("Y-m-d H:i:s"), "{$SCRIPT_URL}", $code, $message, $file, $line);
					$handle = fopen($path, "a");
					if($handle) {
						if(fputcsv($handle, $data)){
							fclose($handle);
						}
						else{
							die("<pre> Unable to forward this request at this time(write logs). </pre>");
						}
					}
					else 
						die("<pre> Unable to forward this request at this time(write logs). </pre>");
				}
				else{
					echo $__NL__LOG_SAVE_PATH;
				}
				//alert message;			
				echo "<pre> Unable to forward this request at this time(SYSTEM FAILED). </pre>";
			}
			die();
		}
	}
	//自定义错误处理
	set_error_handler(array('NL_Exception','error_handler'));
	//自定义异常处理
	set_exception_handler(array('NL_Exception','exception_handler'));
?>